package com.socio.resources;

import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.socio.behaviors.DAOBehavior;
import com.socio.behaviors.UserFacebookIDBehavior;
import com.socio.model.Change;
import com.socio.model.Day;
import com.socio.model.Entry;
import com.socio.model.Event;
import com.socio.model.User;

@Path("/graph")
public class GraphResource {
	
	@Path("/changes")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
	public String getChanges(String json) {
		Gson gson = new Gson();
		Change change = gson.fromJson(json, Change.class);
		
		// setup behaviors
        DAOBehavior userFacebookIDDAO = new UserFacebookIDBehavior();
        
        // for each entry
        for(Entry entry : change.getEntry()) {
        
        	// find user with facebook id
			String facebookID = Long.toString(entry.getUid());
	        Object result = userFacebookIDDAO.read(facebookID, null);
	        List<User> dbUsers = (List<User>)result;
	        if(dbUsers.isEmpty() || dbUsers.get(0) == null)
	        	continue;
	        
	        // get today from user or make it
	        User user = dbUsers.get(0);
	        Day day = null;
	        if(user.getDays().size() > 0)
	        	day = user.getDays().get(0);
	        if(day == null || day.getStartTime() != getDayStartTime()) {
	        	day = new Day();
	        	day.setStartTime(getDayStartTime());
	        	day.setUser(user);
	        	user.getDays().add(day);
	        }
	        
	        // add event to today
	        for(String changedField : entry.getChangedFields()) {
	        	Event event = new Event();
	        	event.setType("Facebook");
	        	event.setChange(changedField);
	        	event.setDay(day);
	        	day.getEvents().add(event);
	        	day.incrementQuickScore();
	        	user.incrementQuickScore();
	        }
	        
	        userFacebookIDDAO.create(user);
        }
        
        return "done";
	}
	
	@Path("/changes")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
	public String verifySubscription(@QueryParam("hub.challenge") String challenge, 
			@QueryParam("hub.verify_token") @DefaultValue("") String verifyToken) {
		
		if(verifyToken.equalsIgnoreCase("monkey"))
			return challenge;
		
		return "false";
		
	}
	
	private long getDayStartTime() {
		long now = System.currentTimeMillis();
		long startTime = now - (now % 86400000);
		
		return startTime;
	}

}
